#!/usr/bin/env python3
"""
简单的 HTTP 服务器用于测试 MCP Tool
"""

import json
import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/mcp/action_required_logger', methods=['POST'])
def action_required_logger():
    """MCP Tool 的 HTTP 接口"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"success": False, "error": "Missing JSON data"}), 400
        
        # 提取参数
        email_id = data.get('email_id')
        email_info_json = data.get('email_info_json')
        sop_json = data.get('sop_json')
        generated_reply = data.get('generated_reply')
        action_type = data.get('action_type')
        
        # 验证参数
        if not all([email_id, email_info_json, sop_json, generated_reply, action_type]):
            return jsonify({
                "success": False,
                "error": "Missing required parameters"
            }), 400
        
        # 调用 EmailQA API
        payload = {
            "email_id": email_id,
            "task_id": f"mcp_http_{hash(email_id + action_type)}",
            "email_info_json": email_info_json,
            "sop_json": sop_json,
            "generated_reply": generated_reply,
            "action_type": action_type,
            "created_by": "mcp_http_server"
        }
        
        response = requests.post(
            "http://localhost:5000/api/email_pending_task/",
            json=payload,
            timeout=30
        )
        
        if response.status_code == 201:
            result = response.json()
            return jsonify({
                "success": True,
                "message": "Email task submitted successfully",
                "task_id": result.get("task_id"),
                "data": result.get("data", {})
            })
        else:
            return jsonify({
                "success": False,
                "error": f"API request failed: {response.text}"
            }), 400
            
    except Exception as e:
        return jsonify({
            "success": False,
            "error": f"Internal server error: {str(e)}"
        }), 500

@app.route('/api/mcp/health', methods=['GET'])
def health_check():
    """健康检查"""
    try:
        response = requests.get("http://localhost:5000/api/health", timeout=10)
        if response.status_code == 200:
            return jsonify({
                "success": True,
                "api_healthy": True,
                "api_status": response.json()
            })
        else:
            return jsonify({
                "success": False,
                "api_healthy": False,
                "error": f"API returned status {response.status_code}"
            })
    except Exception as e:
        return jsonify({
            "success": False,
            "api_healthy": False,
            "error": f"Failed to check API health: {str(e)}"
        })

@app.route('/api/mcp/info', methods=['GET'])
def info():
    """获取 MCP 工具信息"""
    return jsonify({
        "success": True,
        "tool_name": "ActionRequiredLogger",
        "description": "Submit email processing tasks to the EmailQA system",
        "version": "1.0.0",
        "endpoints": {
            "action_required_logger": {
                "method": "POST",
                "url": "/api/mcp/action_required_logger",
                "description": "Submit email processing tasks"
            },
            "health": {
                "method": "GET",
                "url": "/api/mcp/health",
                "description": "Check API health status"
            }
        }
    })

if __name__ == "__main__":
    print("MCP Tool HTTP Server")
    print("=" * 40)
    print("Server URL: http://localhost:8080")
    print("Available endpoints:")
    print("  - POST /api/mcp/action_required_logger")
    print("  - GET /api/mcp/health")
    print("  - GET /api/mcp/info")
    print("=" * 40)
    
    app.run(host='0.0.0.0', port=8080, debug=True)